import com.share.rules.config.DroolsHelper;
import com.share.rules.domain.vo.FeeRuleRequest;
import com.share.rules.domain.vo.FeeRuleResponse;
import org.junit.jupiter.api.Test;
import org.kie.api.runtime.KieSession;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class DroolsTest1 {

    @Test
    public void testRuleExecution() {
        String drl = "package com.share.com.share.rules;\n" +
                "import " + FeeRuleRequest.class.getCanonicalName() + ";\n" +
                "global " + FeeRuleResponse.class.getCanonicalName() + " feeRuleResponse;\n" +
                "\n" +
                "rule \"前5分钟免费\"\n" +
                "when\n" +
                "    $r:FeeRuleRequest(durations >= 0 && durations <= 5)\n" +
                "then\n" +
                "    feeRuleResponse.setTotalAmount(0.0);\n" +
                "    feeRuleResponse.setFreePrice(0.0);\n" +
                "    System.out.println(\"前5分钟免费触发\");\n" +
                "end\n" +
                "\n" +
                "rule \"每1小时3元，24小时35\"\n" +
                "when\n" +
                "    $r:FeeRuleRequest(durations > 5 && durations <= 24*60)\n" +
                "then\n" +
                "    double amount = ($r.getDurations() - 5)/60.0 * 3;\n" +
                "    if(amount > 35) amount = 35;\n" +
                "    feeRuleResponse.setTotalAmount(amount);\n" +
                "    System.out.println(\"24小时内费用规则触发，金额=\" + amount);\n" +
                "end";

        // 1️⃣ 创建请求对象
        FeeRuleRequest request = new FeeRuleRequest();
        request.setDurations(30); // 30分钟，触发“每1小时3元”规则

        // 2️⃣ 创建响应对象
        FeeRuleResponse response = new FeeRuleResponse();

        // 3️⃣ 加载规则
        KieSession kieSession = DroolsHelper.loadForRule(drl);

        // 4️⃣ 设置全局变量
        kieSession.setGlobal("feeRuleResponse", response);

        // 5️⃣ 插入 fact
        kieSession.insert(request);

        // 6️⃣ 触发规则
        int firedRules = kieSession.fireAllRules();
        System.out.println("共触发了规则数: " + firedRules);

        // 7️⃣ 结束会话
        kieSession.dispose();

        // 8️⃣ 验证结果
        System.out.println("规则执行结果 response.totalAmount = " + response.getTotalAmount());
        assertEquals(3.0, response.getTotalAmount(), 0.01); // 30分钟按规则应该收费3元
    }
}
